<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="search_form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isresultShow = false"
      />
    </form>
    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <searchResult v-if="isresultShow" :search-text="searchText"></searchResult>
    <!-- 搜索结果 -->
    <!-- 联想建议 -->
    <searchSuggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"></searchSuggestion>
    <!-- 联想建议 -->
     <!-- 搜索历史记录 -->
    <searchHistory @clear-history="history = []" @search="onSearch" :history="history" v-else></searchHistory>
    <!-- 搜索历史记录 -->
  </div>
</template>

<script>
import searchHistory from './components/search-history'
import searchSuggestion from './components/search-suggestion'
import searchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'searchIndex',
  data () {
    return {
      searchText: '',
      isresultShow: false, // 控制搜索结果的显示
      history: getItem('hmtt_history') || []
    }
  },
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  created () {

  },
  watch: {
    history (nVal) {
      setItem('hmtt_history', nVal)
    }
  },
  methods: {
    // 在手机上点击搜索按钮或者敲回车
    onSearch (val) {
      if (val.trim() === '') return this.$toast('请输入搜索内容')
      // 查找搜索历史是否包含当前值
      const index = this.history.indexOf(val)
      // 如果有先删除
      if (index !== -1) {
        this.history.splice(index, 1)
      }
      // 向前一项添加搜索历史
      this.history.unshift(val)
      this.searchText = val
      this.isresultShow = true
    },
    onCancel () {
      this.$router.back()
      this.isresultShow = false
    }
  }
}
</script>

<style scoped lang='less'>
.search-container {
  padding-top: 108px;
  .van-search {
    background: #3295f9;
  }
  .van-search__action {
    color: #fff;
  }
  .search_form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
  }
}
</style>
